<template>
    <div class="background-box">
        <div class="main-box">
            <div class="qr-code">
                <p>扫码登录</p>
                <!-- 二维码 -->
                <div class="qr-box">
                    <div class="disagree" v-show="refresh">
                        <i class="el-icon-refresh" @click="qrcodeRefresh"></i>
                    </div>
                    <vue-qr logo-src="./favicon.ico"
                        :size="300"
                        :margin="0"
                        :auto-color="true"
                        :dot-scale="1"
                        :text="appSrc" />
                </div>
                <span @click="changeToUser">账号登录</span>
            </div>
            <div :class=" isok ? 'left' : 'active' "></div>
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" :hide-required-asterisk="true">
                <div class="title"><img src="../../assets/logo.png" alt=""></div>
                <el-form-item prop="userId">
                    <i class="el-icon-user"></i>
                    <el-input v-model="ruleForm.userId" placeholder="请输入您的ID"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <i class="el-icon-unlock"></i>
                    <el-input v-model="ruleForm.password" placeholder="请输入您的密码"></el-input>
                </el-form-item>
                <el-checkbox-group v-model="checkList">
                    <el-checkbox label="remenber">记住密码</el-checkbox>
                    <br>
                    <el-checkbox label="autologin">免登录</el-checkbox>
                </el-checkbox-group>
                <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
                <span @click="getQrcode">扫码登录</span>
            </el-form>
        </div>
    </div>

</template>

<script>
    import { MD5, AES, enc } from 'crypto-js'
    import { userInfoApi, userMenuApi, userRightsApi } from '../../apis/userApi'
    import vueQr from 'vue-qr'
    import { autoLoginApi, getAutoCodeApi, getMenuInfoApi, getUserInfoApi, loginApi, loginQrcodeApi, qrcodeLoopApi } from '../../apis/loginApi'

    export default {
        components: {
            vueQr,
        },
        data(){
            return{
                userInfo: {},
                checkList:[],
                isok: true,
                ruleForm: {
                    userId: '',
                    password: ''
                },
                rules: {
                    userId: { required: true, message: '请输入账号', trigger: 'blur' },
                    password: { required: true, message: '请输入密码', trigger: 'blur' }
                },
                appSrc:"",
                timer: null,
                refresh: false,
                over: true
            }
        },
        created(){
            if(!!this.$route.params.msg){
                this.$message.error('token已过期，请重新登录')
            }

            let user = JSON.parse(localStorage.getItem('userInfo'))
            
            if(!!user && !!user.autotoken && user.autotoken !== ''){
                this.checkList.push('autologin')
                let code = AES.decrypt(user.autotoken, '123456').toString(enc.Utf8)
                autoLoginApi({code}).then(res => {
                    console.log(res);
                    if(res.code === 200){
                        this.$store.commit('common/mutationToken',res.token)
                        this.getAutoCode()
                        this.getUserInfo({id: res.id})
                        this.queryUserRights()
                    }else{
                        this.$message.error('登录失败，请重新登录')
                        user.autotoken = ''
                        localStorage.setItem('userInfo',JSON.stringify(user))
                    }
                })
            }

            if(!!user && !!user.id && !!user.pwd){
                this.ruleForm.userId = user.id
                this.ruleForm.password = AES.decrypt(user.pwd, '123456').toString(enc.Utf8)
                this.checkList.push('remenber')
            }
            
        },
        mounted(){
        },
        beforeDestroy(){
            clearTimeout(this.timer)
        },
        methods: {
            // 获取二维码
            getQrcode(){
                if(this.isok === true){
                    this.isok = !this.isok
                    this.over = true
                    this.refresh = false
                }
                loginQrcodeApi().then(res => {
                    if(res.code === 200){
                        this.appSrc = res.qrcode
                        let timeOver = setTimeout(() => {
                            timeOver = null
                            console.log('过期了，刷新我！！！');
                            this.over = false
                            this.refresh = true
                        },63000)
                        if(this.over === true){
                            this.loop()
                        }
                    }
                })
            },
            // 轮询获取扫描结果
            loop(){
                this.timer = setTimeout(() => {
                    clearTimeout(this.timer)
                    qrcodeLoopApi({qrcode: this.appSrc}).then(res => {
                        if(res.code === 200){
                            this.$store.commit('common/mutationToken',res.token)
                            // 获取用户信息
                            let params = { id: res.userid }
                            this.getUserInfo(params)
                            return
                        }
                        if(res.code === 304){
                            this.$message.error(res.message);
                            this.refresh = true
                            return
                        }
                        if(res.code === 400){
                            this.$message.error(res.message);
                            return
                        }
                        if(this.over === true){
                            clearTimeout(this.timer)
                            this.loop()
                        }
                    })
                },500)
            },
            // 去到用户密码登录
            changeToUser(){
                clearTimeout(this.timer)
                this.isok = !this.isok
            },
            // 二维码刷新
            qrcodeRefresh(){
                this.getQrcode()
                this.refresh = false
                this.over = true
            },
            // 获取用户信息
            getUserInfo(params){
                getUserInfoApi(params).then(res => {
                    if(res.code === 200){
                        this.$store.commit('common/mutationUserInfo',res.data)
                        this.getMenuInfo()
                    }else{
                        console.log('获取用户信息失败');
                    }
                })
            },
            // 获取菜单信息
            getMenuInfo(){
                getMenuInfoApi().then(res => {
                    if(res.code === 200){
                        this.$store.commit('common/mutationMenuList',res.data.rows)

                        sessionStorage.setItem('routes',JSON.stringify(res.data.rows))

                        /** 请求回来的菜单数据，只有有path值得数据需要生成route对象 */
                        res.data.rows.reduce((routes, it) => {
                            if (!!it.path) {
                                // 这个@代表 'src'
                                routes.push({path: it.path, component: () => import('@/pages' + it.path)})
                            }
                            this.$router.addRoute('a',{path: it.path.slice(1), component: () => import('@/pages' + it.path), meta: {address: it.name}})

                            return routes

                        }, [])

                        this.queryUserRights()
                    }
                })
            },
            // 获取免登录票据
            getAutoCode(){
                getAutoCodeApi().then(res => {
                    if(res.code === 200){
                        // 保存免登录的token
                        // let a = localStorage.getItem('userInfo')
                        // if(!!a){
                        //     this.userInfo = JSON.parse(a)
                        // }
                        this.userInfo.autotoken = AES.encrypt(res.autocode,'123456').toString()
                        console.log(this.userInfo);
                        localStorage.setItem('userInfo',JSON.stringify(this.userInfo))
                    }else{
                        console.log('获取免登录票据失败');
                        
                    }
                })
            },
            // 查询用户权限
            queryUserRights(){
                userRightsApi({role: this.$store.getters['common/userInfo'].role}).then(res => {
                    console.log('------------',res);
                    if(res.code === 200){
                        this.$store.commit('common/mutationuserEole',res.data)
                        // 保存用户账号与密码
                        localStorage.setItem('userInfo',JSON.stringify(this.userInfo))
                        this.$router.push('/sys/home')
                    }
                })
            },
            // 用户密码登录提交
            submitForm(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let id = ''
                        let data = {
                            id: this.ruleForm.userId,
                            password: MD5(this.ruleForm.password).toString()
                        }
                        loginApi(data).then(res => {
                            if(res.code === 200){
                                // 保存后端返回的token
                                this.$store.commit('common/mutationToken',res.token)
                                id = res.userid

                                // 判断是否记住密码和免登录
                                this.checkList.forEach(item => {
                                    if(item === 'remenber'){
                                        this.userInfo.pwd = AES.encrypt(this.ruleForm.password,'123456').toString()
                                        this.userInfo.id = this.ruleForm.userId
                                    }else{
                                        let information = JSON.parse(localStorage.getItem('userInfo'))
                                        delete information.id
                                        delete information.pwd
                                        localStorage.setItem('userInfo',JSON.stringify(information))
                                    }

                                    console.log(this.userInfo);
                                    if(item === 'autologin'){
                                        // 获取免登录票据
                                        this.getAutoCode()
                                    }
                                })

                                // 获取用户信息
                                let params = {id}
                                this.getUserInfo(params)
                            }else{
                                this.$message.error(res.message);
                            }
                        })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            }
        }
    }
</script>

<style lang="less" scoped>
.background-box{
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, rgb(95, 183, 255), rgb(0, 81, 255));
    .main-box{
        width: 700px;
        height: 500px;
        background-color: white;
        position: fixed;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        margin: auto;
        .qr-code{
            width: 300px;
            height: calc(100% - 100px);
            padding: 50px 20px;
            text-align: center;
            float: left;
            p{
                font-size: 18px;
                color: #555;
                margin-top: 30px;
            }
            .qr-box{
                width: 300px;
                height: 300px;
                position: relative;
                background-color: darkblue;
                .disagree{
                    width: 300px;
                    height: 300px;
                    position: absolute;
                    top: 0;
                    left: 0;
                    background-color: rgba(0, 0, 0,.7);
                    .el-icon-refresh{
                        font-size: 70px;
                        margin-top: 116px;
                        color: #fff;
                        &:hover{
                            color:#05b0ff;
                            cursor: pointer;
                        }
                    }
                }
                .qrcode {
                    display: inline-block;
                    width: 132px;
                    height: 132px;
                    background-color: #fff;
                    padding: 6px;
                    box-sizing: border-box;
                }
            }
            span{
                font-size: 12px;
                cursor: pointer;
                color: #999;
                position: absolute;
                top: 30px;
                left: 30px;
            }
        }
        .left{
            width: 340px;
            height: 100%;
            overflow: hidden;
            position: absolute;
            left: 0;
            top: 0;
            z-index: 99;
            box-shadow: 10px 0px 10px rgba(3, 3, 3, 0.2);
            overflow: hidden;
            background: url(../../assets/right.jpg) no-repeat 0px 0px;
            background-size: 100% 100%;
            transition: left 0.4s linear, box-shadow 0.3s linear;
        }
        .active{
            width: 340px;
            height: 100%;
            overflow: hidden;
            position: absolute;
            left: 360px;
            top: 0;
            z-index: 99;
            box-shadow: -10px 0px 10px rgba(3, 3, 3, 0.2);
            overflow: hidden;
            background: url(../../assets/right.jpg) no-repeat 0px 0px;
            background-size: 100% 100%;
            transition: left 0.4s linear, box-shadow 0.3s linear;
        }
        .el-form{
            width: 310px;
            height: calc(100% - 100px);
            padding: 50px 15px;
            float: right;
            position: relative;
            .title{
                text-align: center;
                width: 300px;
                height: 60px;
                margin-top: 20px;
                margin-bottom: 20px;
                img{
                    width: 70%;
                    height: 70%;
                }
            }
            .el-form-item{
                width: 250px;
                border: 0 solid #000;
                border-bottom: 1px solid #999;
                margin-bottom: 30px;
                margin-left: 25px;
                .el-input{
                    width: 200px;
                }
                .el-icon-user,.el-icon-unlock{
                    font-size: 20px;
                    color: #666;
                }
            }
            .is-checked ::v-deep{
                span{
                    color: #666 !important;
                }
            }
            .el-checkbox-group{
                margin-left: 25px;
                .el-checkbox{
                    display: inline-block;
                    margin-bottom: 10px;
                    color: #999;
                    font-size: 12px;
                }
            }
            .el-button{
                width: 300px;
                height: 40px;
                border: 0 solid #000;
                background: rgb(0, 162, 255);
                margin-top: 30px;
                &:hover{
                    background-color:  #ff6600;
                }
            }
            span{
                font-size: 12px;
                color: #999;
                cursor: pointer;
                position: absolute;
                top: 30px;
                right: 30px;
            }
        }
        .demo-ruleForm ::v-deep{
            .el-form-item__content{
                margin-left: 0 !important;
                .el-input__inner{
                    display: inline-block;
                    border: 0 solid #000;
                }
            }
        }
    }
}
</style>